# This file is part of the AutoMAT distribution (https://bitbucket.com/mahomaho/AutoMAT).
# Copyright (c) 2021 Mattias Holmqvist.
# 
# AutoMAT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# AutoMAT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with AutoMAT.  If not, see <https://www.gnu.org/licenses/>.

from .support import *
import lxml.etree as _ET
import os as _os
import sys as _sys

# this list is the list of all objects to be imported when importing * of AutoMAT
__all__ = ['autosar','autosar_r4p0','LoadFile','default','ModelNone','validator','aggregation_validator']
# set import path to import correct version schema version
if not 'AUTOSAR_RELEASE' in _os.environ:
	_autosar_release = 'AUTOSAR_00052'
else:
	_autosar_release=_os.environ['AUTOSAR_RELEASE']
__path__.append(_os.path.join(_os.path.dirname(__file__), _autosar_release))
#import relevant objects
from . import autosar_r4p0
# init the loaded modules
#autosar_r4p0.Group._init()
autosar_r4p0._init()

# create the root autosar object
autosar_r4p0.AUTOSAR._parent=ModelNone
autosar=autosar_r4p0.AUTOSAR()
autosar._xml=[]


_ET.register_namespace('AR',"http://autosar.org/schema/r4.0")
_schema=_ET.XMLSchema(file=_os.path.join(_os.path.dirname(__file__), autosar_r4p0.schemafile.replace('AutoMAT', '.')))
def _vprint(*args, **kwargs):
    '''Debug print function redirected to stdout if loader started with verbose flag -v'''
    pass
_parser = _ET.XMLParser(remove_blank_text=True,collect_ids=False,remove_comments=False)

def LoadFile(file):
	from . import files
	fileH=files.get(file)
	if hasattr(fileH,'_root'):
		return fileH
	try:
		tree = _ET.parse(str(fileH), _parser)
	except (OSError,_ET.XMLSyntaxError):
		xsi = "http://www.w3.org/2001/XMLSchema-instance"
		tree = _ET.Element(
			"{"+autosar_r4p0.AR_NS+"}AUTOSAR",
			attrib={"{" + xsi + "}schemaLocation": autosar_r4p0.schemaLocation},
			nsmap={'xsi': xsi, None: autosar_r4p0.AR_NS}
		)
		fileH._root=_ET.ElementTree(tree)
		tree=fileH._root
		with open(str(fileH), 'wb') as f:
			f.write(_ET.tostring(fileH._root,pretty_print=True, xml_declaration=True, encoding='utf-8'))
		tree = _ET.parse(str(fileH), _parser)
	try:
		_schema.assertValid(tree)
	except _ET.DocumentInvalid:
		print(f"Error in file {_schema.error_log[0].filename}:", file=_sys.stderr)
		for error in _schema.error_log:
			print(f"\tline {error.line}: Error {error.type},{error.type_name}: {error.message}", file=_sys.stderr)
	root=tree.getroot()
	model=autosar_r4p0.AUTOSAR()
	model._setxml(tree.getroot(),None,ModelNone)
	autosar._merge(model)
	fileH._root=tree
	return fileH

# make sure that the file gets loaded
from . import modelMethods as __modelMethods
